package com.yan.lesson01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class TalkSend implements Runnable{
    private DatagramSocket socket = null;
    private BufferedReader reader = null;

    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) throws SocketException {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;
        socket = new DatagramSocket(fromPort);
        reader = new BufferedReader(new InputStreamReader(System.in));
    }
    @Override
    public void run() {
        while (true) {
            try {
                String data = reader.readLine();
                byte[] buffer = data.getBytes();
                DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length, new InetSocketAddress(this.toIP, this.toPort));
//            发送包
                socket.send(packet);
                if (data.equals("bye")) {
                    break;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
//        关闭socket
        socket.close();

    }
    public static void main(String[] args) {

    }
}
